package com.example.service;

import com.example.domain.Clazz;
import com.example.repository.ClazzRepository;
import com.example.util.EasyuiResult;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ClazzService {
    
    @Autowired
    private ClazzRepository clazzRepository;
    
    @Autowired
    private ScoreService scoreService;
    
    @Autowired
    private ScheduleService scheduleService;
    
    @Autowired
    private StudentService studentService;
    
    /**
     * 根据clazz id 获取clazz详细数据,如果clazzid不存在,会返回空值
     *
     * @param id clazzid
     * @return clazz对象, 有可能是空值
     */
    public Clazz getById(@NotNull int id) {
        log.debug("ClazzService 根据 clazzid={} ,查询clazz详细信息", id);
        return clazzRepository.findById(id).orElseGet(Clazz::new);
    }
    
    /**
     * 查询所有clazz,并按照easyUI格式返回
     *
     * @return easyUI-datagrid数据类型
     */
    public EasyuiResult<Clazz> getAllClazz() {
        log.debug("ClazzService.getAllClazz查询clazz");
        final Iterable<Clazz> all;
        all = clazzRepository.findAll();
        final ArrayList<Clazz> list = Lists.newArrayList(all);
        return (EasyuiResult<Clazz>) new EasyuiResult((long) list.size(), list);
    }
    
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void delete(final int[] ids) {
        log.debug("ClazzService.delete查询clazz,ids={}", ids);
        //删除clazz的同时,还要将clazz对应的学生信息,课程信息,成绩信息一并删除.
        final List<Integer> clazzids = Ints.asList(ids);
        
        //1. 先删成绩
        scoreService.deleteByClazzId(clazzids);
        //2. 课程
        scheduleService.deleteByClazzId(clazzids);
        
        //3. 学生
        studentService.deleteByClazzId(clazzids);
    
        final Iterable<Clazz> all = clazzRepository.findAllById(clazzids);
        clazzRepository.deleteAll(all);
        // clazzRepository.deleteByIdIn(ids);
        // final List<Clazz> collect = clazzids.stream().map(i -> {
        //     Clazz clazz = new Clazz();
        //     clazz.setId(i);
        //     return clazz;
        // }).collect(Collectors.toList());
        // clazzRepository.deleteAll(collect);
    }
    
    @Transactional
    public Clazz save(final Clazz clazz) {
        
        final Clazz result = clazzRepository.save(clazz);
        return result;
        
    }
    
    public List<Clazz> getAll() {
        
        final Iterable<Clazz> all = clazzRepository.findAll();
        return Lists.newArrayList(all);
    }
}
